package org.marsdonne.commons;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public interface VerifiableSignature {

    default String generate(String key) {
        final StringBuilder signBuilder = new StringBuilder(SignatureUtils.convertToUrl(this)).append("&key=").append(key);
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(signBuilder.toString().getBytes(StandardCharsets.UTF_8));
            return SignatureUtils.byteArray2HexStr(md.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    default void sign(String key) {
        this.keepRandomFactor(SignatureUtils.generateRandomString(32));
        this.keepSign(generate(key));
    }

    default boolean verify(String key) {
        String signed = loadSign();
        keepSign(null);//避免签名参与签名生成算法
        String comparedSign = generate(key);
        boolean compared = signed != null && signed.equals(comparedSign);
        keepSign(signed);//校验后恢复签名
        return compared;
    }

    void keepRandomFactor(String factor);

    void keepSign(String signature);

    String loadSign();
}
